#include "stdafx.h"
#include "dataqueue.h"

DataQueue::DataQueue()
:m_nMaxQueueSize(100)
{
	m_pHead = m_pTail = NULL;
	m_nQueueSize = 0;

}
DataQueue::DataQueue( int max_size )
:m_nMaxQueueSize(max_size)
{
	m_pHead = m_pTail = NULL;
	m_nQueueSize = 0;
}

DataQueue::~DataQueue()
{
	Flush();
}

AVDATA* DataQueue::Enqueue( AVDATA * pkt )
{
	AVDATA *pop = NULL;
	Mutex m(m_cs);
	if( m_pHead==NULL ) // empty
	{
		m_pHead = m_pTail = pkt;
		m_pHead->next = m_pTail->next = NULL;
		m_nQueueSize = 1;
	}
	else if( m_nQueueSize>=m_nMaxQueueSize ) // do not encrease queue
	{
		pop = m_pHead;
		m_pHead = m_pHead->next;
		pop->next = NULL;
		m_pTail->next = pkt;
		m_pTail = m_pTail->next;
		m_pTail->next = NULL;
	}
	else
	{
		m_pTail->next = pkt;
		m_pTail = m_pTail->next;
		m_pTail->next = NULL;
		m_nQueueSize++;
	}

	return pop;
}

AVDATA* DataQueue::Dequeue( )
{
	Mutex m(m_cs);
	AVDATA *pkt = 0;
	if( m_nQueueSize==0 )
		pkt = NULL;
	else if( m_nQueueSize==1 )
	{
		pkt = m_pHead;
		m_pHead = m_pTail = NULL;
		m_nQueueSize = 0;
	}
	else
	{
		pkt = m_pHead;
		m_pHead = m_pHead->next;
		m_nQueueSize--;
		pkt->next = NULL;
	}
	return pkt;
}

AVDATA* DataQueue::GetHeader()
{
	return m_pHead;
}

AVDATA* DataQueue::GetTail()
{
	return m_pTail;
}

void	DataQueue::Flush()
{
	AVDATA *pkt=0;
	Mutex m(m_cs);
	while( m_pHead!=NULL)
	{
		pkt = m_pHead;
		m_pHead = m_pHead->next;
		delete pkt;
	}
	m_pTail = NULL;
	m_nQueueSize = 0;
}


